package com.shanhesoft.java.common.config;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.shanhesoft.java.common.core.constant.CommonConstants;
import com.shanhesoft.java.common.core.util.Result;
import com.shanhesoft.java.common.core.util.StringUtil;
import com.shanhesoft.java.common.rancher.type.Container;
import com.shanhesoft.java.modules.exam.domain.VirtualTrainingDetailInstance;
import com.shanhesoft.java.modules.exam.service.VirtualTrainingDetailInstanceService;
import com.shanhesoft.java.modules.exam.service.impl.RancherService;

@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
public class StopContainerScheduleTask {
	
	@Autowired
	private VirtualTrainingDetailInstanceService virtualTrainingDetailInstanceService;
	@Autowired
	private RancherService rancherService;

	@Async
    @Scheduled(fixedDelay = 1000*60)  //间隔1分钟
	public void stopContainers() {
		List<VirtualTrainingDetailInstance> list = virtualTrainingDetailInstanceService.findTimeOutTrainingDetailInstance();
		for (VirtualTrainingDetailInstance virtualTrainingDetailInstance : list) {
			String containerId = virtualTrainingDetailInstance.getContainerId();
			if(StringUtil.isEmpty(containerId)) {
				continue;
			}
			Result<Container> stopContainer = rancherService.stopContainer(containerId);
			if(CommonConstants.FAIL.intValue() == stopContainer.getCode()) {
				continue;
			}
			virtualTrainingDetailInstance.setContainerState("stopped");
			virtualTrainingDetailInstanceService.saveOrUpdate(virtualTrainingDetailInstance);
		}
	}
}
